package com.whjz.utils;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.InputStream;
import java.util.Properties;

@Slf4j
public class SFtpUtils {
  private static Session session = null;
  private static Channel channel = null;
  private static int timeout = 60000;

  /**
   * @param userName
   * @param password
   * @param ip
   * @param port
   * @param dstDirPath 上传服务器目录
   * @param fileName 上送文件名
   */
  public static boolean uploadFile(
      String userName,
      String password,
      String ip,
      String port,
      String dstDirPath,
      String fileName,
      InputStream inputStream) {
    boolean flag = false;
    ChannelSftp channel = null;
    try {
      channel = getChannel(userName, password, ip, port);
      log.info("文件上送服务器");
      String dstFilePath = dstDirPath + fileName;
      try {
        createDir(dstDirPath, channel);
      } catch (Exception e) {
        flag = false;
        log.error("创建路径失败{}", e);
      }
      log.info("====>>目录[{}]创建成功！", dstDirPath);
      channel.put(inputStream, dstFilePath);
      log.info("文件[{}]上送完成", fileName);
      flag = true;
    } catch (Exception e) {
      log.error("=====>>文件上传失败{}", e);
    } finally {
      // 关闭资源
      if (channel != null) {
        channel.quit();
      }
      closeChannel();
    }
    return flag;
  }

  /**
   * 获取通道对象
   *
   * @param userName
   * @param password
   * @param ip
   * @param port
   * @return
   * @throws Exception
   * @throws JSchException
   */
  public static ChannelSftp getChannel(String userName, String password, String ip, String port)
      throws Exception, JSchException {
    JSch jsch = new JSch();
    session = jsch.getSession(userName, ip, Integer.valueOf(port));
    if (password != null) {
      session.setPassword(password);
    }
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.setTimeout(timeout);
    session.connect();
    channel = session.openChannel("sftp");
    channel.connect();
    return (ChannelSftp) channel;
  }

  /** 关闭连接 */
  public static void closeChannel() {
    if (channel != null) {
      channel.disconnect();
    }
    if (session != null) {
      session.disconnect();
    }
  }

  /** 删除文件 */
  public static void delete(
      String userName, String password, String ip, String port, String dirPath, String picName) {
    try {
      ChannelSftp sftp = getChannel(userName, password, ip, port);
      File file = new File(dirPath + picName);
      if (!file.isDirectory()) {
        sftp.cd(dirPath);
        sftp.rm(picName);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** 创建一个文件目录 */
  public static void createDir(String createpath, ChannelSftp sftp) {
    try {
      if (isDirExist(createpath, sftp)) {
        sftp.cd(createpath);
        return;
      }
      String pathArry[] = createpath.split("/");
      StringBuffer filePath = new StringBuffer("/");
      for (String path : pathArry) {
        if (path.equals("")) {
          continue;
        }
        filePath.append(path + "/");
        if (isDirExist(filePath.toString(), sftp)) {
          sftp.cd(filePath.toString());
        } else {
          // 建立目录
          sftp.mkdir(filePath.toString());
          // 进入并设置为当前目录
          sftp.cd(filePath.toString());
        }
      }
      sftp.cd(createpath);
    } catch (SftpException e) {
      log.error("创建路径错误{}", e);
    }
  }
  /** 判断目录是否存在 */
  public static boolean isDirExist(String directory, ChannelSftp sftp) {
    boolean isDirExistFlag = false;
    try {
      SftpATTRS sftpATTRS = sftp.lstat(directory);
      isDirExistFlag = true;
      return sftpATTRS.isDir();
    } catch (Exception e) {
      if (e.getMessage().toLowerCase().equals("no such file")) {
        isDirExistFlag = false;
      }
    }
    return isDirExistFlag;
  }
}
